package utils;

import model.VersionBean;
import wrapper.FileWrapper;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * Created by lincl on 2017/5/16.
 */
public class FileUtils {
    // SVN的用户名、密码、远程路径、本地仓库
    public static final String USERNAME = "lincl";
    public static final String PASSWORD = "HG0338";
//    public static final String SVN_PATH = "https://119.29.144.60/svn/anxigov/anxigov";
//    public static final String LOCAL_PATH = "D:\\IdeaProjects\\anxigov";
//    public static final String LOCAL_SRC_PATH = LOCAL_PATH + "\\src";
//    public static final String LOCAL_JAVA_PATH = LOCAL_PATH + "\\java";
//    public static final String CLASS_PATH = LOCAL_PATH+ "\\WebRoot\\WEB-INF\\classes";
//    public static final String OUT_PATH = "D:\\anxigov";

    public static final String SVN_ROOT = "/code/rtoa.web";
    public static final String SVN_PATH = "https://120.39.251.71:8443/svn/saasoa"+ SVN_ROOT;

    public static final String LOCAL_PATH = "D:\\IdeaProjects\\code\\rtoa.web";//本地仓库
    public static final String CLASS_PATH = LOCAL_PATH+ "\\webapp\\WEB-INF\\classes";//编译后类路径
    public static final String OUT_PATH = "D:\\rtoa.web";//输出位置

    public static Set<String> notChkDir = new HashSet<>();
    public static Set<String> notChkPath = new HashSet<>();
    static {
        notChkDir.add( FileUtils.LOCAL_PATH+ "\\.idea" );
        notChkDir.add( FileUtils.LOCAL_PATH+ "\\.settings" );
//        notChkDir.add( FileUtils.LOCAL_PATH+ "\\doc" );
//        notChkDir.add( FileUtils.LOCAL_PATH+ "\\WebRoot\\WEB-INF" );
        notChkDir.add( FileUtils.LOCAL_PATH+ "\\webapp\\WEB-INF" );
        notChkDir.add( FileUtils.LOCAL_PATH+ "\\doc" );
        notChkDir.add( FileUtils.LOCAL_PATH+ "\\classes" );
        notChkDir.add( FileUtils.LOCAL_PATH+ "\\webapp\\upload" );
        notChkDir.add( FileUtils.LOCAL_PATH+ "\\webapp\\ueditor" );
        notChkDir.add( FileUtils.LOCAL_PATH+ "\\webapp\\imgfile" );
        notChkDir.add( FileUtils.LOCAL_PATH+ "\\webapp\\dustbin" );
    }

//    public static final String LOCAL_SRC_PATH = LOCAL_PATH + "\\source";
//    public static final String LOCAL_JAVA_PATH = LOCAL_PATH + "\\java";
//    public static final String OUT_SRC_PATH = OUT_PATH + "\\src";
//    public static final String OUT_JAVA_PATH = OUT_PATH + "\\java";



    public static void copyDir(File oldDir, File newDir, IFileModification modification) throws Exception {
        if(!oldDir.exists() || !oldDir.isDirectory())
            return;
        if( newDir.exists() ){
            newDir.delete();
        }
        newDir.mkdirs();

        for(File f: oldDir.listFiles()){
            if(f.isDirectory()){
                copyDir( f, newDir.getPath() + "\\" + f.getName(), modification );
            } else {
                copyFile( f, newDir.getPath() + "\\" + f.getName(), modification );
            }
        }
    }

    public static void copyDir(File oldFile, String newPath, IFileModification modification) throws Exception {
        copyDir( oldFile, new File(newPath), modification );
    }

    public static void copyDir(File oldFile, String newPath) throws Exception {
        copyDir( oldFile, newPath, null );
    }

    public static void copyDir(String oldPath, String newPath) throws Exception {
        copyDir( new File(oldPath), new File(newPath), null );
    }

    public static void copyFile(String oldPath, String newPath) throws Exception {
        copyFile(new File(oldPath), new File(newPath));
    }

    public static void copyFile(File oldFile, String newPath, IFileModification modification) throws Exception {
        copyFile( oldFile, new File(newPath), modification );
    }

    public static void copyFile(File oldFile, String newPath) throws Exception {
        copyFile(oldFile, newPath, null);
    }

    public static void copyFile(File oldFile, File newFile, IFileModification modification) throws Exception {
        if(modification != null){
            FileWrapper fileWrapper = new FileWrapper(oldFile, newFile);
            modification.doAction(fileWrapper);
            oldFile = fileWrapper.getOldFile();
            newFile = fileWrapper.getNewFile();
        }

       /* //如果是java文件 去取编译的class文件
        if(oldFile.getPath().lastIndexOf(".java")!=-1){
            oldFile = new File(oldFile.getPath().replace(LOCAL_SRC_PATH, CLASS_PATH).replace(".java", ".class"));
            newFile = new File(newFile.getPath().replace(".java", ".class"));
        }*/

        if(!oldFile.exists() || !oldFile.isFile())
            return;
        if( !newFile.exists() ){
            if( !newFile.getParentFile().exists() )
                newFile.getParentFile().mkdirs();
        } else
            newFile.createNewFile();

        InputStream is = null;
        OutputStream os = null;
        try {
            is = new FileInputStream(oldFile);
            os = new FileOutputStream(newFile);
            byte[] buffer = new byte[1024];
            int byteRead = 0; // 读取的字节数
            while ( (byteRead = is.read(buffer)) != -1){
                os.write(buffer, 0, byteRead);
            }
        } catch (Exception e){
            e.printStackTrace();
            throw e;
        } finally {
            if(os!=null) os.close();
            if(is!=null) is.close();
        }
    }

    public static void copyFile(FileWrapper fileWrapper, IFileModification modification) throws Exception {
        if(modification != null){
            modification.doAction(fileWrapper);
        }
        copyFile(fileWrapper.getOldFile(), fileWrapper.getNewFile());
    }


    public static void copyFile(File oldFile, File newFile) throws Exception {
        copyFile(oldFile, newFile, null);
    }




    //解压文件
    public static int unZip(File file, String dest) {
        ZipFile zf = null;
        InputStream is = null;
        FileOutputStream fos = null;
        Runtime runtime = Runtime.getRuntime();
        try {
            zf = new ZipFile(file);
            File versionDir = new File(file.getParent(), file.getName().substring(0, file.getName().lastIndexOf(".")));

            Enumeration entries = zf.entries();
            ZipEntry entry = null;
            String command;
            while (entries.hasMoreElements()) {
                entry = (ZipEntry) entries.nextElement();
                if (entry.isDirectory()) {
                    String dirPath = dest + File.separator + entry.getName();
                    File dir = new File(dirPath);
                    dir.mkdirs();
                    dir = new File(versionDir + File.separator + entry.getName());
                    dir.mkdirs();
                } else {
                    // 表示文件
                    File destFile = new File(dest + File.separator + entry.getName());
                    File f = new File(versionDir + File.separator + entry.getName());
                    if (!f.exists()) {
                        File parentDir = new File(f.getParent());
                        parentDir.mkdirs();
                    }
                    f.createNewFile();
                    // 将压缩文件内容写入到这个文件中
                    is = zf.getInputStream(entry);
                    fos = new FileOutputStream(f);
                    int count;
                    byte[] buf = new byte[8192];
                    while ((count = is.read(buf)) != -1) {
                        fos.write(buf, 0, count);
                    }
                    is.close();
                    fos.close();

//                    Platform.runLater(new Runnable() {
//                        public void run() {
//                            String command = "cmd /c copy /y D:\\IdeaProjects\\svnPacking\\out\\artifacts\\svnPacking\\bundles\\svnPacking\\app\\svnPacking.jar " +
//                                    "D:\\idea\\test\\svnPacking\\app\\svnPacking.jar";
//                            try {
//                                Runtime.getRuntime().exec(command);
//                            } catch (IOException e) {
//                                e.printStackTrace();
//                            }
//                        }
//                    });

                    command = "cmd /c copy /y "+ f.getPath() +" "+ destFile.getPath();
                    runtime.exec(command);

//                    f.renameTo(destFile);
                }
            }
            return 1;
        } catch (Exception e1) {
            e1.printStackTrace();
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                }
            }

            if(fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                }
            }
            return 0;
        }
    }

    //读取版本文件
    public static VersionBean readVersionBean(File file){
        if(file.exists()){
            VersionBean versionBean = new VersionBean();
            BufferedReader bufferedReader = null;
            try {
                bufferedReader = new BufferedReader(new FileReader(file));
                String s = bufferedReader.readLine();
                if(s.indexOf("=")!=-1){
                    String curVer = s.split("=")[1];
                    versionBean.setCurVersion(curVer);
                }

                s = bufferedReader.readLine();
                s = bufferedReader.readLine();
                while (s!=null && !"".equals(s)){
                    versionBean.addVersion(s.split(" ")[0]);
                    s = bufferedReader.readLine();
                }
                return versionBean;
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            } finally {
                try {
                    if(bufferedReader!=null){
                        bufferedReader.close();
                    }
                } catch (IOException e1) {
                }
            }

        }
        return null;
    }

    //从服务器下载文件
    public static int downLoadFile(File file){
        HttpURLConnection httpUrl = null;
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        URL url = null;
        InputStream is = null;
        try {
            url = new URL(Constant.DOWN_LOAD_PATH + file.getName());
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            byte[] buffer = new byte[1024];
            int size = 0;
            is = httpUrl.getInputStream();
            bis = new BufferedInputStream(is);
            fos = new FileOutputStream(file);
            while ((size = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, size);
                fos.flush();
            }
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        } finally {
            try {
                if(fos!=null){
                    fos.close();
                }
            } catch (IOException ex3) {
            }
            try {
                if(bis!=null){
                    bis.close();
                }
            } catch (IOException ex3) {
            }
            try {
                if(is!=null){
                    is.close();
                }
            } catch (IOException ex3) {
            }
            try {
                if(httpUrl!=null){
                    httpUrl.disconnect();
                }
            } catch (Exception ex3) {
            }
        }
    }
}
